<?php

namespace app\meizhuangapi\controller\meizhuang;
use app\meizhuangapi\controller\Controller;
use think\Request;
use app\meizhuangapi\model\meizhuang\MeizhuangComment as MeizhuangCommentModel;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use app\meizhuangapi\model\Order as OrderModel;
use app\meizhuangapi\model\Setting as SettingModel;

/**
 * 美妆-订单评价控制器
 */
class Comment extends Controller{
    protected $tag=[];
    protected $MeizhuangComment;

    public function _initialize(Request $request = null){
        $this->MeizhuangComment=new MeizhuangCommentModel();
        $this->tag=[
            '飞粉','正品','色号','质量','黑黄皮','适合淡妆','容易上妆','易过敏'
        ];
    }
    /*
     * 获取评价标签
     */
    public function getTag(){
        return $this->renderSuccess($this->tag,'获取成功');
    }
    /*
     * 评价
     */
    public function add(){
        $data['order_id']=input('post.order_id');
        $data['wuliuStar']=input('post.wuliuStar');
        $data['fuwuStar']=input('post.fuwuStar');
        $data['wxapp_id']=input('post.wxapp_id');
        $data['create_time']=time();
        $data['update_time']=0;
        $data['type']=input('post.type');//1:初评 2：追评
        $data['goods_id']=input('post.goods_id');
        $user = $this->getUser(false);
        $data['user_id']=$user['user_id'];
        $jsonInfo=htmlspecialchars_decode(input('post.commentInfo'));
        $pingjiaInfo=$this->isJson($jsonInfo);
        if(!$pingjiaInfo){
            return $this->renderError([],'commentInfo字段格式不正确');
        }
        $jsonInfo=json_decode($jsonInfo,true);
        //return $this->renderSuccess($jsonInfo,'评价成功2');
        foreach ($jsonInfo as $k=>$v){
            $info['order_id']=$data['order_id'];
            $info['wuliuStar']=$data['wuliuStar'];
            $info['wxapp_id']=$data['wxapp_id'];
            $info['type']=$data['type'];
            $info['create_time']=time();
            $info['update_time']=0;
            $info['status']=1;
            $info['user_id']=$data['user_id'];
            $info['imageids']=$v['imageids'];
            $info['tag']=$v['tag'];
            $info['goods_id']=$v['goods_id'];
            $info['content']=$v['content'];
            $info['miaoshuStar']=$v['miaoshuStar'];
            $info['fuwuStar']=$data['fuwuStar'];
            $this->MeizhuangComment->addPingjia($info);
            //更新订单评论状态
            Db::name('order')->where(['order_id'=>$data['order_id']])->update(['is_comment'=>1]);
        }
        return $this->renderSuccess([],'评价成功');
    }
    /*
     * 评价首页
     */
    public function index(){
        $order_id=input('post.order_id');
        $user = $this->getUser(false);
        $data['user_id']=$user['user_id'];
        $model = OrderModel::getUserOrderDetail($order_id, $data['user_id']);
        foreach ($model['goods'] as $k=>$v){
            $model['goods'][$k]['tag']=$this->tag;
        }
        // 该订单是否允许申请售后
        $model['isAllowRefund'] = $model->isAllowRefund();
        return $this->renderSuccess([
            'order' => $model,  // 订单详情
            'setting' => [
                // 积分名称
                'points_name' => SettingModel::getPointsName(),
            ],
        ]);
    }

    /*
     * 图片上传至七牛云
     */
    public function upload(){
        if(request()->method()=='OPTIONS'){
            return true;
        }
        $file=request()->file('image');
        $wxapp_id=input('post.wxapp_id');//小程序id
        //获取七牛配置信息
        $config=Db::name('base_setting')->where(['key'=>'storage'])->find();
        $configArray=json_decode($config['values'],'true');
        $def=$configArray['default'];
        $accessKey=$configArray['engine'][$def]['access_key'];
        $secretKey=$configArray['engine'][$def]['secret_key'];
        //构建鉴权对象
        $auth=new Auth($accessKey, $secretKey);
        //要上传的空间,这是在你七牛后台设置的
        $bucket=$configArray['engine'][$def]['bucket'];
        //生成上传 Token
        $token=$auth->uploadToken($bucket);
        //要上传文件的本地路径
        $filePath=$file->getRealPath();
        //上传到七牛后保存的文件名
        $ext = pathinfo($file->getInfo('name'),PATHINFO_EXTENSION);
        $key = substr(md5($file->getRealPath()),0,5).date('YmdHis').rand(0,9999).'.'.$ext;
        $uploadMgr=new UploadManager();
        list($res,$err)=$uploadMgr->putFile($token, $key, $filePath);
        if($err!==null){
            return json(['msg'=>'上传失败','code'=>'error','data'=>[]]);
        }else{
            //将上传记录写入文件表
            $data['storage']='qiniu';
            $data['group_id']=0;
            $data['file_name']=$res['key'];
            $data['file_size']=$file->getSize();
            $data['file_type']='image';
            $data['extension']=$ext;
            $data['is_user']=0;
            $data['wxapp_id']=$wxapp_id;
            $data['is_recycle']=0;
            $data['is_delete']=0;
            $data['create_time']=time();
            $data['file_url']=$configArray['engine'][$def]['domain'];
            $res1=Db::name('upload_file')->insertGetId($data);
            if($res1){
                //返回文件id和访问地址
                $return['imageUrl']=$configArray['engine'][$def]['domain'].'/'.$res['key'];
                $return['file_id']=$res1;
                return json(['msg'=>'上传成功','code'=>'success','data'=>$return]);
            }
            return json(['msg'=>'上传成功','code'=>'success','data'=>$res]);
        }
    }
    /*
     * 判断参数是否为json字符串
     */
    private function isJson($data='',$assoc=false){
        $data=json_decode($data, $assoc);
        if (($data&&is_object($data))||(is_array($data) && !empty($data))){
            return $data;
        }
        return false;
    }
    /*
     * 获取商品评价列表
     */
    public function getPingJiaList(){
        $remark=input('post.tag');
        $goodWhere['goods_id']=input('post.goods_id');
        $goodWhere['wxapp_id']=input('post.wxapp_id');
        //获取评价标签并标记总数
        $tagCount=[];
        foreach ($this->tag as $k=>$v){
            $flagCount=$this->MeizhuangComment->getCount(['goods_id'=>$goodWhere['goods_id'],'status'=>1,'tag'=>$v]);
            $tagCount[$k]['tag']=$v;
            $tagCount[$k]['count']=$flagCount;
        }
        if(empty($remark)||$remark=='全部'){
            $where['goods_id']=$goodWhere['goods_id'];
        }else{
            $where['goods_id']=$goodWhere['goods_id'];
            $where['tag']=$remark;
        }
        $where['status']=1;
        $commentList=$this->MeizhuangComment->getList($where);
        $return['tagInfo']=$tagCount;
        if($commentList['data']){
            foreach ($commentList['data'] as $k=>$v){
                if(!empty($v['user']['username'])){
                    $commentList['data'][$k]['user']['nickName']=$v['user']['username'];
                }
            }
        }
        $return['commentList']=$commentList;
        $c=Db::name('meizhuang_comment')->where(['goods_id'=>$goodWhere['goods_id'],'status'=>1])->count();
        $return['totalComment']=$c;
        return $this->renderSuccess($return,'获取成功');
    }
    /*
     * 获取店铺详情
     */
    public function getStoreInfo(){
        $wxapp_id=input('post.wxapp_id');
        //粉丝数，综合体验，店铺信息
        $fansCount=Db::name('user')->where(['wxapp_id'=>$wxapp_id])->count();
        $storeInfo=Db::name('store_shop')->where(['wxapp_id'=>$wxapp_id])->find();
        //获取头像，资质图片
        $tx=Db::name('upload_file')->where(['file_id'=>$storeInfo['logo_image_id']])->find();
        $zz=Db::name('upload_file')->where(['file_id'=>$storeInfo['image_id_yyzz']])->find();
        $storeInfo['headImageUrl']=$tx['file_url'].'/'.$tx['file_name'];
        $storeInfo['authImageUrl']=$zz['file_url'].'/'.$zz['file_name'];
        $commentInfo=Db::name('meizhuang_comment')->where(['wxapp_id'=>$wxapp_id])->field('sum(miaoshuStar) as miaoshuStarCount,sum(wuliuStar) as wuliuStarCount,sum(fuwuStar) as fuwuStarCount')->find();
        $total=Db::name('meizhuang_comment')->where(['wxapp_id'=>$wxapp_id])->count();
        if($total==0){
            $comprehensive=0;
        }else{
            $comprehensive=floor(($commentInfo['miaoshuStarCount']+$commentInfo['wuliuStarCount']+$commentInfo['fuwuStarCount'])/(3*$total));
        }
        $data['fansCount']=$fansCount;
        $data['storeInfo']=$storeInfo;
        $data['commentInfo']=$comprehensive;
        return $this->renderSuccess($data,'获取成功');
    }
    /*
     * 关注店铺
     */
    public function lookStore(){
        $user = $this->getUser(false);
        $user_id=$user['user_id'];
        $wxapp_id=input('post.wxapp_id');
        $data['user_id']=$user_id;
        $data['wxapp_id']=$wxapp_id;
        $data['create_time']=time();
        $data['status']=1;
        $data['update_time']=0;
        //判断是否已关注
        $return=Db::name('meizhuang_store_fans')->where(['user_id'=>$user_id,'wxapp_id'=>$wxapp_id])->find();
        if($return){
            return $this->renderError([],'您已关注过，无需重复操作');
        }
        $res=Db::name('meizhuang_store_fans')->insertGetId($data);
        if($res){
            return $this->renderSuccess([],'关注成功');
        }
        return $this->renderError([],'关注失败');
    }
}
